#!/usr/bin/env python3

import pathlib
from quant.data import ricequant, juejin, jisilu
from quant import trader, strategy
from absl import app, flags
import logging
from typing import Dict
from datetime import datetime

FLAGS = flags.FLAGS

flags.DEFINE_string('cache_dir', '~/.cache/quant/conbond', 'Cache directory')
flags.DEFINE_string('start_date', None, 'Data start date')
flags.DEFINE_string('end_date', None, 'Data end date')
flags.DEFINE_enum('freq', '1d', ['1d', '1m'], 'k bar frequency')
flags.DEFINE_enum('source', None,
                  ['ricequant', 'joinquant', 'juejin', 'jisilu'],
                  'Data source to refresh')
flags.mark_flag_as_required('source')
flags.DEFINE_string('params_vars', None, 'Conbond strategy parameters')
flags.DEFINE_string('strategy', None, 'Strategy name')


def main(_):
    if FLAGS.source == 'ricequant':
        cache_dir = pathlib.Path(FLAGS.cache_dir).joinpath(
            FLAGS.source, FLAGS.end_date).expanduser()
        ricequant.refresh_conbond(FLAGS.start_date, FLAGS.end_date, FLAGS.freq,
                                  cache_dir)
    elif FLAGS.source == 'joinquant':
        # joinquant.refresh_conbond(FLAGS.start_date, FLAGA.end_date, FLAGS.freq, cache_dir)
        raise Exception('Not updated')
    elif FLAGS.source == 'juejin':
        cache_dir = pathlib.Path(FLAGS.cache_dir).joinpath(
            FLAGS.source, FLAGS.end_date).expanduser()
        juejin.refresh_conbond(
            FLAGS.start_date, FLAGS.end_date, FLAGS.freq, cache_dir,
            pathlib.Path(FLAGS.cache_dir).joinpath('jisilu').expanduser())
    elif FLAGS.source == 'jisilu':
        cache_dir = pathlib.Path(FLAGS.cache_dir).joinpath(
            FLAGS.source).expanduser()
        logging.getLogger().setLevel(logging.INFO)
        _, df = jisilu.refresh_now(cache_dir, FLAGS.end_date)
        if FLAGS.strategy is not None:
            pvars: Dict = eval(FLAGS.params_vars)
            td = trader.JuejinTrader()
            td.get_next_trading_date = trader.Trader.trading_date_in_n
            st = strategy.ConbondRotateStrategy(FLAGS.strategy, pvars, td,
                                                lambda context, bar_dict: df)
            st.generate_signal(df, datetime.now())


if __name__ == '__main__':
    app.run(main)
